package movie.mb;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import movie.ejb.EjbUser;
import movie.entity.UserAccess;
import movie.utility.JsfUtil;
import movie.utility.Utility;

@ManagedBean
@SessionScoped
public class MbLogin {

	@EJB
	EjbUser ejbUser;
	private UserAccess logedUser;
	private String userName;
	private String password;
	private static final long serialVersionUID = 1L;

	public MbLogin() {
		System.out.print("Constructor: " + getClass().getName());
		
	}

	@PostConstruct
	public void postConstruct() {
		System.out.print("Post construct: " + getClass().getName());
	}

	public void navigationToHome() {
		FacesContext.getCurrentInstance().getApplication().getNavigationHandler().handleNavigation(
				FacesContext.getCurrentInstance(), null, "home?faces-redirect=true");
	}

	public String login() {
		if (Utility.isStringEmptyOrNull(userName) || Utility.isStringEmptyOrNull(password)) {
			JsfUtil.failValidation();
			JsfUtil.addWarningMessage("Please enter user name and password.");
			return null;
		}
		UserAccess user = ejbUser.login(userName, password);
		if (user == null) {
			JsfUtil.addWarningMessage("Login information incorrect. Please try again.");
			JsfUtil.failValidation();
			return null;
		}
		if (!user.getActive()) {
			JsfUtil.addWarningMessage("Account is being deactivated. Please contact administrator.");
			JsfUtil.failValidation();
			return null;
		}
		logedUser = user;
		System.out.println("User succesfully logged in: " + logedUser.getUserName());
		return "home?faces-redirect=true";
	}

	public void logout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.invalidate();
		navigationToHome();
	}

	public boolean isLoged() {
		if (logedUser == null) {
			return false;
		} else {
			return true;
		}
	}

	public UserAccess getLogedUser() {
		return logedUser;
	}

	public void setLogedUser(UserAccess logedUser) {
		this.logedUser = logedUser;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		System.out.print(userName);
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		System.out.print(userName);
		this.password = password;
	}
}
